#encoding:utf-8
from flask import render_template, request, redirect, url_for, session,g
from sqlalchemy import or_
from models import *
from decorators import login_required
from . import home


@home.route('/')
def index():
    context = {
        "questions": Question.query.order_by('-create_time').all()
    }
    return render_template('index.html', **context)


@home.route('/detail/<question_id>/')
def detail(question_id):
    question_model = Question.query.filter(Question.id == question_id).first()

    return redirect(url_for('home.index',question=question_model))

@home.route('/search/')
def search():
    q = request.args.get('q')
    questions = Question.query.filter(or_(Question.title.contains(q),Question.content.contains(q))).order_by('-create_time')
    return render_template('index.html',questions = questions)



@home.route('/add_answer/', methods=['POST'])
@login_required
def add_answer():
    ans_content = request.form.get('answer_content')
    ques_id = request.form.get('question_id')
    ques = Question.query.filter(Question.id == ques_id).first()

    ans = Answer(content=ans_content)

    ans.question = ques
    ans.author = g.user
    db.session.add(ans)
    db.session.commit()
    return redirect(url_for('home.detail',question_id=ques_id) )


@home.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        tel = request.form.get('telephone')
        psw = request.form.get('password')
        user = User.query.filter(User.telephone == tel).first()
        if user and user.check_pwd(psw):
            session['user_id'] = user.id
            # 如果想在31天内都不需要登录
            session.permanent = True
            print u'登录成功'
            return redirect(url_for('home.index'))
        else:
            return u'手机号码或者密码错误。'


@home.route('/regist/', methods=['GET', 'POST'])
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        telephone = request.form.get('telephone')
        username = request.form.get('username')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        # 手机号码验证，如果被注册了就不能再注册了
        user = User.query.filter(User.telephone == telephone).first()
        if user:
            return u'手机号码已经被注册，请重新输入。'
        else:
            if password1 != password2:
                return u'两次密码不相等，请核对后再填写。'
            else:
                user = User(telephone=telephone, username=username, password=password1)
                db.session.add(user)
                db.session.commit()
                return redirect(url_for('home.login'))


@home.route('/logout')
@login_required
def logout():
    # session.pop('user_id')
    # del session['user_id']
    session.clear()
    return redirect(url_for('home.login'))


@home.route('/question/', methods=['GET', 'POST'])
@login_required
def question():
    if request.method == 'GET':
        return render_template('question.html')
    else:
        title = request.form.get('title')
        content = request.form.get('content')
        ques = Question(title=title, content=content)

        ques.author = g.user
        db.session.add(ques)
        db.session.commit()
        return redirect(url_for('home.index'))
